package model

import (
	"github.com/jmoiron/sqlx"
	"time"
	"zimuzu_cvn_web_api/config"
	. "zimuzu_cvn_web_api/pkg/e"
	"zimuzu_cvn_web_api/pkg/errno"
)

type CvnAmountDb struct {
	Uid           int64   `db:"uid"`
	Total         float64 `db:"total"`
	Balance       float64 `db:"balance"`
	FrozenBalance float64 `db:"frozen_balance"`
	CreateTime    int64   `db:"create_time"`
	UpdateTime    string  `db:"update_time"`
	SignString    string  `db:"sign_string"`
	SignVersion   string  `db:"sign_version"`
}

type UpdateCvnAmountDb struct {
	Uid          int64   `db:"uid"`
	Amount       float64 `db:"balance"`
	FrozenAmount float64 `db:"frozen_balance"`
	SignString   string  `db:"sign_string"`
	SignVersion  string  `db:"sign_version"`
}

//获取CVNT账户信息
//Auth: TXG
func GetCvnAmount(db sqlx.Queryer, uid int64) (qi CvnAmountDb, err error) {
	err = sqlx.Get(db, &qi, "SELECT uid,balance,frozen_balance,create_time,update_time,sign_string,sign_version FROM cvn_amount WHERE uid = ?", uid)
	if err != nil {
		Log("err", err)
	}
	return qi, err
}

/*
 * @ Author: hupfei
 * @ Description: 初始化cvn_amount
 **/
func InitCvnAmount(uid int64, signString, signVersion string) (err error) {
	notTime := time.Now().Unix()
	_, err = config.C.DB.DB.Exec("INSERT INTO cvn_amount (uid,create_time,sign_string,sign_version) VALUES (?,?,?,?)", uid, notTime, signString, signVersion)
	if err != nil {
		Log("err", "初始化cvn_amount失败:", err.Error())
	}
	return
}

//修改CVNT账户信息
//Auth: TXG
func UpdateCvnAmount(db sqlx.Execer, data UpdateCvnAmountDb) (err error) {
	res, err := db.Exec("UPDATE cvn_amount SET balance = balance + ?, frozen_balance = frozen_balance + ?, sign_string = ?, sign_version = ? WHERE uid = ?", data.Amount, data.FrozenAmount, data.SignString, data.SignVersion, data.Uid)
	if err != nil {
		Log("err", "UpdateCvnAmountBlance:", data.Uid, err.Error())
		return err
	}
	row, err := res.RowsAffected()
	if err != nil {
		Log("err", "UpdateCvnAmountBlance:", data.Uid, err.Error())
		return err
	}
	if row != 1 {
		Log("err", "UpdateCvnAmountBlance:", data.Uid, "影响行数为:", row)
		err = errno.UpdateDataErr
		return err
	}
	return nil
}
